<?php

namespace app\common\library\util;

use fast\Random;
use think\Hook;
use app\common\library\Email;

class Ems{
    protected static $expire = 120;
    protected static $maxTimes = 5;
    public static function send($email,$source='云课堂平台')
    {
        $status = ['code'=>-1];
        $emsModel = new \app\common\model\Ems();
        // $emsModel->startTrans();
        $ems = $emsModel->where('email',$email)->find();
        if($ems){
            if($ems['createtime']+self::$expire<time()){
                $ems->delete();
                $ems = null;
            }else if($ems['times']>=self::$maxTimes){
                $status['msg'] = '请求次数过多，请稍后再试';
                return $status;
            }
        }
        

        $data = [
            'event' => 'default',
            'email' => $email,
            'code' => Random::alnum(4),
            'times' => 1,
            'ip' => request()->ip(),
            'createtime' => time(),
        ];
        
        if(!$ems){
            $emsModel->save($data);
        }else{
            $data['times'] = $ems['times']+1;
            $emsModel->save($data,['id'=>$ems['id']]);
        }
        if (!Hook::get('ems_send')) {
            //采用框架默认的邮件推送
            Hook::add('ems_send', function ($params) use($source){
                $obj = new Email();
                $subject = "【{$source}】请查收你的验证码！";
                $message = "你的验证码是：" . $params['code'] . "，" . ceil(self::$expire / 60) . "分钟内有效。";
                // $subject = "胡俊同学你好";
                // $message = "打开的是小狗";
                $result = $obj
                    ->to($params['email'])
                    ->subject($subject)
                    ->message($message)
                    ->send();
                return $result;
            });
        }
        $result = Hook::listen('ems_send', $data, null, true);
        if (!$result) {
            $ems->delete();
            $status['code'] = 0;
            $status['msg'] = '验证码发送失败，请重新发送或者修改邮箱';
            return $status;
        }
        $status['code'] = 1;
        $status['msg'] = '发送验证码成功';
        return $status;
    }
    public static function checkCode($email,$code)
    {
        $status = ['code'=>-1];
        $emsModel = new \app\common\model\Ems();
        $ems = $emsModel->where('email',$email)->find();
        if($ems['createtime']+self::$expire>time())
        {
            if(strtolower($ems['code'])==strtolower($code))
            {
                $status['code'] = 1;
                $status['msg'] = '验证成功';
            }else{
                $status['code'] = 0;
                $status['msg'] = '验证码错误';
            }
        }else{
            $status['code'] = -1;
            $status['msg'] = '验证码已过期';
        }
        return $status;
    }
}